package org.jeecg.modules.news_order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.boot.starter.rabbitmq.client.RabbitMqClient;
import org.jeecg.common.base.BaseMap;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.constant.rabbitConstant;
import org.jeecg.modules.news_order.entity.NewsOrder;
import org.jeecg.modules.news_order.mapper.NewsOrderMapper;
import org.jeecg.modules.news_order.service.INewsOrderService;
import org.jeecg.modules.news_shop.entity.NewsShop;
import org.jeecg.modules.news_shop.mapper.NewsShopMapper;
import org.jeecg.modules.nurse_user.entity.NurseUser;
import org.jeecg.modules.nurse_user.mapper.NurseUserMapper;
import org.jeecg.modules.nurse_user_orders.entity.NurseUserOrders;
import org.jeecg.modules.system.entity.SysAnnouncement;
import org.jeecg.modules.vedio_order.entity.VedioOrder;
import org.jeecg.modules.vedio_order.mapper.VedioOrderMapper;
import org.jeecg.modules.vedio_shop.mapper.VedioShopMapper;
import org.jeecg.modules.wechat.service.WechatPaymentService;
import org.jeecg.modules.wechat.utils.WXPaySignatureCertificateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @Description: 资讯订单
 * @Author: jeecg-boot
 * @Date:   2025-07-05
 * @Version: V1.0
 */
@Service
public class NewsOrderServiceImpl extends ServiceImpl<NewsOrderMapper, NewsOrder> implements INewsOrderService {
    @Autowired
    private NurseUserMapper nurseUserMapper;

    @Autowired
    private NewsShopMapper newsShopMapper;

    @Autowired
    private WechatPaymentService wechatPaymentService;

    @Autowired
    private NewsOrderMapper newsOrderMapper;


    @Autowired
    private RabbitMqClient rabbitMqClient;

    @Value("${wechat.nurse.expiry-time:}")
    private Integer expiryTime;

    @Value("${wechat.nurse.appid:}")
    private String APP_ID;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseMap addByWeChat(NewsOrder newsOrder,String mchId) {

        NurseUser nurseUser = nurseUserMapper.selectById(newsOrder.getUserId());

        if (nurseUser == null) {
            throw new JeecgBootException("未查询到用户");
        }
        NewsShop newsShop = newsShopMapper.selectById(newsOrder.getNewsId());
        if (newsShop == null) {
            throw new JeecgBootException("未查询到资讯");
        }
        BaseMap map = new BaseMap();


        String orderId = UUIDGenerator.generate();

        BigDecimal amt = new BigDecimal(0);

        NewsOrder newsOrder1 = new NewsOrder();

        newsOrder1.setCode(orderId);
        newsOrder1.setStatus("1");
        newsOrder1.setUserId(nurseUser.getId());
        newsOrder1.setOutTradeNo(orderId);
        newsOrder1.setOrderText("资讯下单");
        newsOrder1.setPrice(newsShop.getPrice());
        newsOrder1.setNum("1");
        newsOrder1.setNewsId(newsOrder.getNewsId());
        newsOrder1.setTotalPrice(newsShop.getPrice());
        newsOrder1.setSysOrgCode(newsOrder.getSysOrgCode());
        Long total = newsShop.getPrice().multiply(BigDecimal.valueOf(100)).longValue();

        map.put("total", total);
        map.put("description", newsOrder1.getOrderText());
        map.put("out_trade_no", newsOrder1.getOutTradeNo());
        map.put("openid", nurseUser.getOpenid());
        map.put("type","2");

        try {
            map = wechatPaymentService.weChatDoUnifiedOrder(map,mchId);

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (!map.get("code").equals(200)) {
            throw new JeecgBootException("微信下单失败！！！！" + map.toString());
        }

        newsOrder1.setPrepayid(map.get("prepayid"));

        newsOrderMapper.insert(newsOrder1);


        map.put("out_trade_no", orderId);

        Integer expiry_time = 1000 * expiryTime;

        rabbitMqClient.sendMessage(rabbitConstant.DELAY_QUEUE_ORDER_NAME, map, expiry_time);
        //log.info("订单编号：[{}] 进入延迟队列...", orderId);
        return map;
    }

    @Override
    public BaseMap payByWeChat(String out_trade_no) {

        BaseMap map = new BaseMap();

        NewsOrder newsorder = newsOrderMapper.selectById(out_trade_no);

        if (oConvertUtils.isEmpty(newsorder)) {
            throw new JeecgBootException("未查询到订单");
        }
        if (!newsorder.getStatus().equals("1")) {
            throw new JeecgBootException("未查询到待支付订单");
        }

        try {
            map.put("mchId", newsorder.getMchId());
            map.put("prepayid", newsorder.getPrepayid());
            map = WXPaySignatureCertificateUtil.jsApiPay(map, APP_ID);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    @Override
    public NewsOrder successPay(NewsOrder newsOrder) {

        newsOrder.setStatus("2");

        newsOrderMapper.updateById(newsOrder);

        return newsOrder;
    }

    @Override
    public List<Map<String, Object>> listByWeChat(String beginDate, String endDate, String userId,String newsId, String status) {
        return newsOrderMapper.listByWeChat(userId,newsId,status);
    }


    @Override
    public void payNotify(HttpServletRequest request, String mchId) {

        BaseMap map = wechatPaymentService.weChatNotificationHandler(request,mchId);

        if (!map.get("code").equals(200)) {
            return;
        }
        NewsOrder newsOrder = newsOrderMapper.selectOne(new QueryWrapper<NewsOrder>().eq("out_trade_no", map.get("out_trade_no")));

        if (oConvertUtils.isEmpty(newsOrder)) {
            return;
        }

        if (newsOrder.getStatus().equals("2") ) {
            return;
        }
        successPay(newsOrder);
    }
}
